<template>
  <view class="enroll">
    <view class="nesting">
      <image src="/static/login/nesting.png" mode="" />
    </view>
    <!-- 注册 -->
    <tabTopBar :title="$t('enrollPage.enroll')" :bgColor="'transparent'" />

    <view class="content" :style="{ height: contentHeight + 'px' }">
      <up-form
        labelPosition="left"
        :model="enrollFrom"
        :rules="rules"
        ref="uFormRef"
      >
        <!-- 账号 -->
        <up-form-item prop="username" borderBottom>
          <!-- placeholder="请输入账号" -->
          <up-input
            v-model="enrollFrom.username"
            prefixIcon="account"
            prefixIconStyle="font-size: 40upx;color: #FFF"
            class="loginInfo-input"
            :placeholder="$t('enrollPage.pleaseEnterAccount')"
            border="none"
            color="#fff"
            :clearable="true"
          >
            <template #suffix>
              <text style="color: #fff">*</text>
            </template>
          </up-input>
        </up-form-item>

        <!-- 密码 -->
        <up-form-item prop="password" borderBottom>
          <!-- placeholder="请输入密码" -->
          <up-input
            v-model="enrollFrom.password"
            :type="showPassword ? 'text' : 'password'"
            class="loginInfo-input"
            :placeholder="$t('enrollPage.pleaseEnterPassword')"
            color="#fff"
            prefixIconStyle="font-size: 40upx;color: #FFF"
            prefixIcon="lock"
          >
            <template #suffix>
              <view class="look-pasword">
                <template v-if="showPassword">
                  <image
                    src="/static/login/eye.png"
                    style="width: 28upx"
                    mode="widthFix"
                    @click="showPassword = false"
                  />
                </template>
                <template v-else>
                  <up-icon
                    @click="showPassword = true"
                    name="eye-fill"
                    color="#ffffff"
                    size="20"
                  ></up-icon>
                </template>
              </view>
            </template>
          </up-input>
        </up-form-item>
        <!-- 再次输入密码 -->
        <up-form-item prop="confirmPassword" borderBottom>
          <!-- placeholder="请再次输入密码" -->
          <up-input
            v-model="enrollFrom.confirmPassword"
            :type="showPasswordTo ? 'text' : 'password'"
            class="loginInfo-input"
            :placeholder="$t('enrollPage.pleaseEnterPasswordAgain')"
            color="#fff"
            prefixIconStyle="font-size: 40upx;color: #FFF"
            prefixIcon="lock"
          >
            <template #suffix>
              <view class="look-pasword">
                <template v-if="showPasswordTo">
                  <image
                    src="/static/login/eye.png"
                    style="width: 28upx"
                    mode="widthFix"
                    @click="showPasswordTo = false"
                  />
                </template>
                <template v-else>
                  <up-icon
                    @click="showPasswordTo = true"
                    name="eye-fill"
                    color="#ffffff"
                    size="20"
                  ></up-icon>
                </template>
              </view>
            </template>
          </up-input>
        </up-form-item>
        <!-- 企业 -->
        <up-form-item borderBottom>
          <!-- placeholder="请输入企业" -->
          <up-input
            v-model="enrollFrom.companyName"
            class="loginInfo-input"
            :placeholder="$t('enrollPage.pleaseEnterTheCompany')"
            border="none"
            color="#fff"
            :clearable="true"
          >
            <template #prefix>
              <image
                src="/static/login/enterprise.png"
                style="width: 32upx"
                mode="widthFix"
              />
            </template>
            <template #suffix>
              <!-- <text style="color: #fff">*</text> -->
            </template>
          </up-input>
        </up-form-item>
        <!-- 真实姓名 -->
        <up-form-item prop="nickName" borderBottom>
          <!-- placeholder="请输入真实姓名" -->
          <up-input
            v-model="enrollFrom.nickName"
            class="loginInfo-input"
            :placeholder="$t('enrollPage.pleaseEnterYourRealName')"
            border="none"
            color="#fff"
            :clearable="true"
          >
            <template #prefix>
              <view style="padding-top: 10rpx">
                <image
                  src="/static/login/name.png"
                  style="width: 32upx"
                  mode="widthFix"
                />
              </view>
            </template>
            <template #suffix>
              <text style="color: #fff">*</text>
            </template>
          </up-input>
        </up-form-item>
        <!-- 电话号码 -->
        <up-form-item prop="phoneNumber" borderBottom>
          <!-- placeholder="请输入电话" -->
          <up-input
            v-model="enrollFrom.phoneNumber"
            class="loginInfo-input"
            :placeholder="$t('enrollPage.pleaseEnterAPhoneNumber')"
            border="none"
            color="#fff"
            :clearable="true"
          >
            <template #prefix>
              <view class="prefix-class">
                <image
                  src="/static/login/user-phone.png"
                  style="width: 34rpx"
                  mode="widthFix"
                />
                +
                <input
                  v-model="enrollFrom.code"
                  :placeholder="t('phone.code')"
                  border="none"
                  color="#fff"
                  style="width: 80rpx"
                  :clearable="true"
                  :rules="codeRules"
                />
                <view class="shu"></view>
              </view>
            </template>
            <!-- <template #suffix>
              <text style="color: #fff">*</text>
            </template> -->
          </up-input>
        </up-form-item>
        <!-- 邮箱 -->
        <up-form-item prop="email" borderBottom>
          <!-- placeholder="请输入邮箱" -->
          <up-input
            :placeholder="$t('enrollPage.pleaseEnterYourEmailAddress')"
            v-model="enrollFrom.email"
            class="loginInfo-input"
            color="#fff"
            prefixIconStyle="font-size: 40upx;color: #FFF"
          >
            <template #prefix>
              <view style="padding-top: 10upx">
                <image
                  src="/static/login/email.png"
                  style="width: 34upx"
                  mode="widthFix"
                />
              </view>
            </template>
          </up-input>
        </up-form-item>
        <!-- 邮箱验证码 -->
        <up-form-item prop="emailCode" borderBottom>
          <!-- placeholder="请输入邮箱验证码" -->
          <up-input
            :placeholder="$t('enrollPage.pleaseEnterAVerificationCode')"
            v-model="enrollFrom.emailCode"
            class="loginInfo-input"
            color="#fff"
            prefixIconStyle="font-size: 40upx;color: #FFF"
          >
            <template #prefix>
              <view style="padding-top: 10upx">
                <image
                  src="/static/login/email.png"
                  style="width: 34upx"
                  mode="widthFix"
                />
              </view>
            </template>
            <template #suffix>
              <view class="prefix-class">
                <view class="shu" style="margin: 0 15rpx 0 0"></view>

                <template v-if="isCountdown">
                  <text style="color: #64b7f6; margin-right: 15rpx">
                    <!-- 获取验证码 -->
                    {{ timeNum + "S" }}
                  </text>
                </template>
                <template v-else>
                  <text
                    style="color: #64b7f6; margin-right: 15rpx"
                    @click="getVerificationCode"
                  >
                    <!-- 获取验证码 -->
                    {{ $t("enrollPage.getAVerificationCode") }}
                  </text>
                </template>

                <text style="color: #fff">*</text>
              </view>
            </template>
            <text style="color: #fff">*</text>
          </up-input>
        </up-form-item>

        <up-form-item borderBottom>
          <!-- 注册 -->
          <up-button
            type="primary"
            class="btn-submit"
            :text="$t('enrollPage.enrollBtn')"
            :disabled="!checkboxType"
            @click="handleEnroll"
          ></up-button>
        </up-form-item>
      </up-form>
      <view class="select-checkbox">
        <up-checkbox-group
          v-model="checkboxValue"
          placement="column"
          @change="checkboxChange"
          :checked="true"
        >
          <up-checkbox
            :customStyle="{
              marginRight: '5upx',
              marginTop: '0',
              marginBottom: '0',
            }"
            activeColor="#64B7F6"
            size="15"
            label=""
            name="check"
          >
          </up-checkbox>
        </up-checkbox-group>
        <view class="checkout-text">
          <!-- 已阅读并同意 -->
          {{ $t("enrollPage.readsAndAgrees") }}
          <text
            class="agreement"
            @click="goAgreement('userAgreement', $t('privacy.userAgreement'))"
          >
            《
            <!-- 用户协议 -->
            {{ $t("enrollPage.userAgreement") }}
            》
          </text>
          <!-- 和 -->
          {{ $t("enrollPage.and") }}
          <text
            class="agreement"
            @click="
              goAgreement('privacyAgreement', $t('privacy.privacyAgreement'))
            "
          >
            《
            <!-- 隐私协议 -->
            {{ $t("enrollPage.privacyAgreement") }}
            》
          </text>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive } from "vue";
import { useAppStore } from "@/store/app";
const contentHeight = ref(0);
const uFormRef = ref(null);
import apis from "@/apis/index.js";

import { useI18n } from "vue-i18n";
const { t } = useI18n();

const showPassword = ref(false);
const showPasswordTo = ref(false);
const checkboxValue = ref(["check"]);
const checkboxType = ref(true);

const enrollFrom = reactive({
  username: "", //	账号
  password: "", // 密码
  confirmPassword: "", //	确认密码		true
  companyName: "", //	公司名称		true
  nickName: "", //	姓名		true
  email: "", //	邮箱号码		true
  emailCode: "", //	邮箱验证码		true
  phoneNumber: "", //	手机号		false
  code: "", // 区号
});
const timer = ref(null);
const isCountdown = ref(false);
const timeNum = ref(60);
const rules = reactive({
  username: [
    {
      required: true,
      message: t("enrollPage.pleaseEnterAccount"),
      trigger: ["change", "blur"],
    },
    {
      validator: async (rule, value, callback) => {
        const regex = /^(?=.*[a-zA-Z0-9])[a-zA-Z0-9\W_]+$/;
        if (!regex.test(value)) {
          callback(
            new Error(t("enrollPage.accountMustBeEnglishOrEnglishAndNumbers"))
          );
          return;
        }
        try {
          const res = await apis.checkUsernameExists({ username: value });
          console.log("res", res);
          if (res.code == 200) {
            callback();
          } else {
            callback(new Error(res.data));
          }
        } catch (error) {
          console.log("error", error);
          // 处理请求错误
          callback(new Error(error.data));
        }
      },
      trigger: ["blur"],
    },
  ],
  password: [
    {
      required: true,
      message: t("enrollPage.pleaseEnterPassword"),
      trigger: ["blur"],
    },
    {
      validator: (rule, value, callback) => {
        if (value && value.length < 6) {
          callback(
            new Error(t("enrollPage.passwordCannotBeLessThanSixCharacters"))
          );
        } else {
          callback();
        }
      },
      trigger: ["blur"],
    },
  ],
  confirmPassword: [
    {
      required: true,
      message: t("enrollPage.pleaseEnterPasswordAgain"),
      trigger: ["blur"],
    },
    {
      validator: (rule, value, callback) => {
        if (value !== enrollFrom.password) {
          callback(new Error(t("enrollPage.passwordsDoNotMatch")));
        } else {
          callback();
        }
      },
      trigger: ["blur"],
    },
  ],
  nickName: {
    required: true,
    message: t("enrollPage.pleaseEnterYourRealName"),
    trigger: ["blur"],
  },
  phoneNumber: [
    {
      validator: (rule, value, callback) => {
        if (!value) {
          // 如果没有填写电话号码，不做任何校验
          callback();
          return;
        }

        // 提取区号
        const code = enrollFrom.code;
        const codeRegex = /^\s*\d{1,3}$/;
        if (!codeRegex.test(code)) {
          callback(new Error(t("enrollPage.invalidCodeFormat")));
          return;
        }

        // 校验电话号码是否为纯数字
        const phoneRegex = /^\d+$/;
        if (!phoneRegex.test(value)) {
          callback(new Error(t("enrollPage.pleaseEnterAPhoneNumber")));
          return;
        }
        callback();
      },
      trigger: ["blur", "change"],
    },
  ],
  email: [
    {
      required: true,
      message: t("enrollPage.pleaseEnterYourEmailAddress"),
      trigger: ["blur"],
    },
    {
      validator: async (rule, value, callback) => {
        if (!value) {
          callback(new Error(t("enrollPage.pleaseEnterYourEmailAddress")));
          return;
        }
        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
        if (!emailRegex.test(value)) {
          callback(new Error(t("enrollPage.invalidEmailFormat")));
          return;
        }
        // 移除验证邮箱是否已被注册的逻辑
        callback();
      },
      trigger: ["blur"],
    },
  ],

  emailCode: [
    {
      required: true,
      message: t("enrollPage.pleaseEnterTheEmailVerificationCode"),
      trigger: ["blur", "change"],
    },
    {
      validator: async (rule, value, callback) => {
        // 校验是否为 6 位数字
        const codeRegex = /^\d{6}$/;
        if (!codeRegex.test(value)) {
          callback(
            new Error(t("enrollPage.pleaseEnterTheEmailVerificationCode"))
          );
          return;
        }

        // try {
        //   // 假设 apis 中有一个 checkEmailCode 方法用于校验验证码
        //   const res = await apis.checkEmailExists(value, enrollFrom.email);
        //   if (res.code === 200) {
        //     callback();
        //   } else {
        //     callback(new Error(t("enrollPage.invalidEmailCodeFormat")));
        //   }
        // } catch (error) {
        //   // 处理请求错误
        //   callback(new Error(error.data));
        // }
      },
      trigger: ["blur", "change"],
    },
  ],
});
// 校验邮箱格式的函数
const validateEmail = (email) => {
  const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;
  return emailRegex.test(email);
};
// 获取验证码的方法
const getVerificationCode = async () => {
  const email = enrollFrom.email;
  if (!validateEmail(email)) {
    // 邮箱格式不正确，不调用获取验证码的接口
    uFormRef.value.validateField("email");
    return;
  }
  apis.checkUserEmailExists({ email: email }).then((res) => {
    if (res.code == 200) {
      isCountdown.value = true;
      timer.value = setInterval(function () {
        timeNum.value--;
        // 当倒计时为0时，启用按钮并清除计时器
        if (timeNum.value == 0) {
          clearInterval(timer.value);
          timeNum.value = 60;
          isCountdown.value = false;
        }
      }, 1000);
      uni.showToast({
        title: res.data,
        icon: "none",
      });
    }
  });
};

const checkboxChange = (e) => {
  if (!e || e.length < 1) {
    checkboxType.value = false;
  } else {
    checkboxType.value = true;
  }
  console.log(checkboxType.value);
};

const handleEnroll = () => {
  uFormRef.value
    .validate()
    .then((valid) => {
      if (valid) {
        let params = {
          companyName: enrollFrom.companyName,
          confirmPassword: enrollFrom.confirmPassword,
          email: enrollFrom.email,
          emailCode: enrollFrom.emailCode,
          nickName: enrollFrom.nickName,
          password: enrollFrom.password,
          phoneNumber: enrollFrom.phoneNumber
            ? "+" + enrollFrom.code + "-" + enrollFrom.phoneNumber
            : "",
          username: enrollFrom.username,
        };
        apis.userRegistration(params).then((res) => {
          if (res.code == 200) {
            uni.navigateTo({
              url: `/pages/outcomeType/outcomeType?title=${t(
                "enrollPage.success"
              )}`,
            });
          }
        });
      } else {
      }
    })
    .catch(() => {
      // 处理验证错误
    });
};
// const goAgreement = (params) => {
//   uni.navigateTo({
//     url: `/pages/agreement/agreement?params=${params}`,
//   });
// };
const goAgreement = (params, name) => {
  uni.navigateTo({
    url: `/pages/agreement/agreement?type=${params}&title=${name}`,
  });
};
const init = () => {
  const useStore = useAppStore();
  let navbarHeightNum = useStore.getNavBarHeight();
  let statusBarHeightNum = useStore.geStatusBarHeight();
  let windowHeight = uni.getSystemInfoSync().windowHeight;
  contentHeight.value = windowHeight - navbarHeightNum - statusBarHeightNum;
};

init();
</script>

<style lang="scss" scoped>
.enroll {
  width: 100%;
  height: 100vh;
  background: linear-gradient(180deg, #172c40, #08121e);
  position: relative;
  overflow: hidden;
  box-sizing: border-box;

  .nesting {
    width: 960upx;
    height: 1320upx;
    position: absolute;
    top: -100upx;
    left: 145upx;
    /* 让点击事件穿透该元素 */
    pointer-events: none;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .content {
    width: 100%;
    box-sizing: border-box;
    text-align: center;
    overflow-y: scroll;
    padding: 80rpx 30upx 30rpx 30upx;
    box-sizing: border-box;

    .loginInfo-input {
      width: 100%;
      height: 88upx;
      background-color: #222d49;
      border-radius: 150upx;
      z-index: 1;
      padding: 0 36upx !important;
      box-sizing: border-box;

      .prefix-class {
        width: 100%;
        display: flex;
        justify-content: flex-start;
        align-items: center;
        color: rgb(192, 196, 204);
        font-size: 26rpx;
        box-sizing: border-box;

        .shu {
          width: 24rpx;
          height: 0px;
          transform: rotate(90deg);
          opacity: 1;
          margin-left: 15rpx;
          border: 1px solid #596072;
        }
      }
    }

    .look-pasword {
      display: flex;
      justify-content: center;
      align-items: center;
    }

    :deep(.u-form-item__body__right__message) {
      text-align: left;
    }

    .btn-submit {
      width: 100%;
      height: 88upx;
      border-radius: 150upx;
      border: none;
      font-family: Alibaba PuHuiTi 3;
      font-size: 32upx;
      font-weight: 500;
      text-align: center;
      font-variation-settings: "opsz" auto;
    }

    .select-checkbox {
      width: 100%;
      display: flex;
      justify-content: flex-start;
      align-items: flex-start;

      .checkout-text {
        font-family: Alibaba PuHuiTi 2;
        font-size: 24upx;
        font-variation-settings: "opsz" auto;
        /* 白 */
        color: #ffffff;

        .agreement {
          font-family: Alibaba PuHuiTi 2;
          font-weight: 400;
          font-size: 24upx;
          font-variation-settings: "opsz" auto;
          border-bottom: 1px solid #fff;
        }
      }
    }

    .btns {
      width: 100%;
      margin-top: 100upx;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      .btns-item {
        width: 33.33%;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;

        .image {
          width: 96upx;
          height: 96upx;
          border: 1px solid #202934;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 24upx;
        }
      }

      .btns-item-text {
        font-family: Alibaba PuHuiTi 3;
        font-size: 28upx;
        font-variation-settings: "opsz" auto;
        color: #eeeeee;
      }
    }

    .select-checkbox {
      width: 100%;
      margin-top: 30rpx;
      padding: 0 0 50rpx 0;
      box-sizing: border-box;
      display: flex;
      justify-content: center;
      align-items: flex-start;

      .checkout-text {
        font-family: Alibaba PuHuiTi 2;
        font-size: 24upx;
        font-variation-settings: "opsz" auto;
        /* 白 */
        color: #ffffff;

        .agreement {
          font-family: Alibaba PuHuiTi 2;
          font-weight: 400;
          font-size: 24upx;
          font-variation-settings: "opsz" auto;
          border-bottom: 1px solid #fff;
        }
      }
    }
  }
}
</style>
